package com.chenj.springbootehcache.service.impl;


import com.chenj.springbootehcache.entity.User;
import com.chenj.springbootehcache.service.EhcacheService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class EhcacheServiceImpl implements EhcacheService {

    @Cacheable(value="UserCache", key="'user:' + #userId")//user:1000
    //@Cacheable(value="UserCache", keyGenerator="selfKeyGenerate")//user:1000
    @Override
    public User findById(String userId) {
        System.out.println("execute findById....");
        return new User("1000","Jack");
    }


    // 将缓存保存进UserCache中，并当参数userId的长度小于12时才保存进缓存，
    @Cacheable(value="UserCache", condition="#userId.length() < 12")
    public boolean isReserved(String userId) {
        System.out.println("UserCache:"+userId);
        return false;
    }


    @CachePut(value="UserCache", key="#key")
    public String refreshData(String key) {
        System.out.println("模拟从数据库中加载数据");
        return key + "::" + String.valueOf(Math.round(Math.random()*1000000));
    }

    //清除掉UserCache中某个指定key的缓存
    @CacheEvict(value="UserCache",key="'user:' + #userId")
    public void removeUser(String userId) {
        System.out.println("UserCache:"+userId);
    }

    //allEntries：true表示清除value中的全部缓存，默认为false
    //清除掉UserCache中全部的缓存
    @CacheEvict(value="UserCache", allEntries=true)
    public void removeAllUser() {
        System.out.println("UserCache delete all");
    }


}
